local extension = Package("joy_xhly")
extension.extensionName = "joy"

Fk:loadTranslationTable{
  ["joy_xhly"] = "欢乐-星火燎原",
}

local U = require "packages/utility/utility"



local xiahouba = General(extension, "joy__xiahouba", "shu", 4)
local baobian = fk.CreateTriggerSkill{
  name = "joy__baobian",
  anim_type = "masochism",
  frequency = Skill.Compulsory,
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      table.find({"joy__tiaoxin", "joyex__paoxiao", "joyex__shensu"}, function(s) return not player:hasSkill(s, true) end)
  end,
  on_use = function(self, event, target, player, data)
    for _, s in ipairs({"joy__tiaoxin", "joyex__paoxiao", "joyex__shensu"}) do
      if not player:hasSkill(s, true) then
        player.room:handleAddLoseSkills(player, s, nil, true, false)
        return
      end
    end
  end,
}
xiahouba:addSkill(baobian)
xiahouba:addRelatedSkill("joy__tiaoxin")
xiahouba:addRelatedSkill("joyex__paoxiao")
xiahouba:addRelatedSkill("joyex__shensu")
Fk:loadTranslationTable{
  ["joy__xiahouba"] = "夏侯霸",
  ["#joy__xiahouba"] = "棘途壮志",

  ["joy__baobian"] = "豹变",
  [":joy__baobian"] = "锁定技，当你受到伤害后，你依次获得以下一个技能：〖挑衅〗、〖咆哮〗、〖神速〗。",
}





local sunluyu = General(extension, "joy__sunluyu", "wu", 3, 3, General.Female)
local meibu = fk.CreateTriggerSkill{
  name = "joy__meibu",
  anim_type = "control",
  events = {fk.EventPhaseStart, fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.EventPhaseStart then
        return target.phase == Player.Play and target ~= player and not player:isNude()
      elseif event == fk.AfterCardsMove and player:usedSkillTimes(self.name, Player.HistoryTurn) > 0 then
        for _, move in ipairs(data) do
          if move.skillName == "ty__zhixi" then
            for _, info in ipairs(move.moveInfo) do
              if player.room:getCardArea(info.cardId) == Card.DiscardPile then
                return true
              end
            end
          end
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      local room = player.room
      local card = room:askForDiscard(player, 1, 1, true, self.name, true, ".", "#ty__meibu-invoke::"..target.id, true)
      if #card > 0 then
        self.cost_data = card[1]
        return true
      end
    else
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      room:doIndicate(player.id, {target.id})
      room:throwCard({self.cost_data}, self.name, player, player)
      if target.dead then return end
      local turn = room.logic:getCurrentEvent():findParent(GameEvent.Turn)
      if turn ~= nil and not target:hasSkill("ty__zhixi", true) then
        room:handleAddLoseSkills(target, "ty__zhixi", nil, true, false)
        turn:addCleaner(function()
          room:handleAddLoseSkills(target, "-ty__zhixi", nil, true, false)
        end)
      end
    else
      local ids = {}
      for _, move in ipairs(data) do
        if move.skillName == "ty__zhixi" then
          for _, info in ipairs(move.moveInfo) do
            if room:getCardArea(info.cardId) == Card.DiscardPile then
              table.insertIfNeed(ids, info.cardId)
            end
          end
        end
      end
      local dummy = Fk:cloneCard("dilu")
      dummy:addSubcards(ids)
      room:moveCardTo(dummy, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
    end
  end,
}
sunluyu:addSkill(meibu)
sunluyu:addSkill("ty__mumu")
sunluyu:addRelatedSkill("ty__zhixi")
Fk:loadTranslationTable{
  ["joy__sunluyu"] = "孙鲁育",
  ["#joy__sunluyu"] = "舍身饲虎",

  ["joy__meibu"] = "魅步",
  [":joy__meibu"] = "其他角色的出牌阶段开始时，你可以弃置一张牌，令该角色于本回合内拥有〖止息〗。若其本回合因〖止息〗"..
  "弃置牌后，你获得之。",

  ["$joy__meibu1"] =" ",
  ["$joy__meibu2"] =" ",
  ["$ty__mumu_joy__sunluyu1"] = " ",
  ["$ty__mumu_joy__sunluyu2"] = " ",
  ["~joy__sunluyu"] = " ",

}

local zhugeke = General(extension, "joy__zhugeke", "wu", 3)
local aocai = fk.CreateViewAsSkill{
  name = "joy__aocai",
  pattern = ".|.|.|.|.|basic",
  anim_type = "special",
  expand_pile = function() return Self:getTableMark( "joy__aocai") end,
  prompt = function()
    return "#joy__aocai"
  end,
  card_filter = function(self, to_select, selected)
    if #selected == 0 and table.contains(Self:getTableMark(  "joy__aocai"), to_select) then
      local card = Fk:getCardById(to_select)
      if card.type == Card.TypeBasic then
        if Fk.currentResponsePattern == nil then
          return Self:canUse(card) and not Self:prohibitUse(card)
        else
          return Exppattern:Parse(Fk.currentResponsePattern):match(card)
        end
      end
    end
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    return Fk:getCardById(cards[1])
  end,
  enabled_at_play = function(self, player)
    return false
  end,
  enabled_at_response = function(self, player, response)
    return player.phase == Player.NotActive
  end,
}
local aocai_trigger = fk.CreateTriggerSkill{
  name = "#joy__aocai_trigger",

  refresh_events = {fk.AskForCardUse, fk.AskForCardResponse},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(aocai) and player ~= player.room.current
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local n = player:isKongcheng() and 4 or 3
    local ids = {}
    for i = 1, n, 1 do
      if i > #room.draw_pile then break end
      table.insert(ids, room.draw_pile[i])
    end
    player.room:setPlayerMark(player, "joy__aocai", ids)
  end,
}
local duwu = fk.CreateActiveSkill{
  name = "joy__duwu",
  anim_type = "offensive",
  target_num = 1,
  can_use = function(self, player)
    return player:getMark("@@duwu-turn") == 0
  end,
  card_filter = Util.TrueFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    if #selected == 0 and to_select ~= Self.id then
      local target = Fk:currentRoom():getPlayerById(to_select)
      if target.hp == #selected_cards then
        if table.contains(selected_cards, Self:getEquipment(Card.SubtypeWeapon)) then
          return Self:distanceTo(target) == 1  --FIXME: some skills(eg.gongqi, meibu) add attackrange directly!
        else
          return Self:inMyAttackRange(target)
        end
      end
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:throwCard(effect.cards, self.name, player)
    room:damage{
      from = player,
      to = target,
      damage = 1,
      skillName = self.name,
    }
  end,
}
local duwu_trigger = fk.CreateTriggerSkill{
  name = "#joy__duwu_trigger",
  mute = true,
  events = {fk.EnterDying, fk.AfterDying},
  can_trigger = function(self, event, target, player, data)
    return data.damage and data.damage.skillName == "joy__duwu" and data.damage.from and data.damage.from == player and not player.dead
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    if event == fk.EnterDying then
      data.extra_data = data.extra_data or {}
      data.extra_data.duwu = player.id
    elseif data.extra_data.duwu == player.id and not target.dead then
      local room = player.room
      room:setPlayerMark(player, "@@duwu-turn", 1)
      if not player.dead then
        player:drawCards(1,"joy__duwu")
      end
    end
  end,
}
aocai:addRelatedSkill(aocai_trigger)
duwu:addRelatedSkill(duwu_trigger)
zhugeke:addSkill(aocai)
zhugeke:addSkill(duwu)
Fk:loadTranslationTable{
  ["joy__zhugeke"] = "诸葛恪",
  ["#joy__zhugeke"] = "兴家赤族",
  ["joy__aocai"] = "傲才",
  [":joy__aocai"] = "当你于回合外需要使用或打出一张基本牌时，你可以观看牌堆顶的三张牌（若你没有手牌则改为四张），若你观看的牌中有此牌，你可以使用或打出之。",
  ["joy__duwu"] = "黩武",
  [":joy__duwu"] = "出牌阶段，你可以弃置X张牌对你攻击范围内的一名其他角色造成1点伤害（X为该角色的体力值）。"..
  "若其因此进入濒死状态且被救回，则濒死状态结算后你摸一张牌，且本回合不能再发动〖黩武〗。",
  ["#joy__aocai"] = "傲才：你可以使用或打出其中你需要的基本牌",
  ["#joy__duwu_trigger"] = "黩武",

}


local maliang = General(extension, "joy__maliang", "shu", 3)
maliang:addSkill("zishu")
maliang:addSkill("yingyuan")
Fk:loadTranslationTable{
  ["joy__maliang"] = "马良",
  ["#joy__maliang"] = "白眉智士",
}



local liuyan = General(extension, "joy__liuyan", "qun", 3)
liuyan:addSkill("tushe")
liuyan:addSkill("limu")
Fk:loadTranslationTable{
  ["joy__liuyan"] = "刘焉",
  ["#joy__liuyan"] = "裂土之宗",
}

local panjun = General(extension, "joy__panjun", "wu", 3)
local guanwei = fk.CreateTriggerSkill{
  name = "joy__guanwei",
  anim_type = "support",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target.phase == Player.Play and
      player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and not player:isNude() then
        local suits = {}
        local events = player.room.logic:getEventsOfScope(GameEvent.UseCard, 1, function (e)
          local use = e.data[1]
          if use.from == target.id then
            if table.contains(suits, use.card.suit) then
              return true
            else
              table.insert(suits, use.card.suit)
            end
          end
          return false
        end, Player.HistoryTurn)
        return #events > 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    local cards = player.room:askForDiscard(player, 1, 1, true, self.name, true, ".", "#joy__guanwei-invoke::"..target.id, true)
    if #cards > 0 then
      player.room:doIndicate(player.id, {target.id})
      self.cost_data = cards
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:throwCard(self.cost_data, self.name, player, player)
    if not target.dead then
      target:drawCards(2, self.name)
      target:gainAnExtraPhase(Player.Play)
    end
  end,
}
local gongqing = fk.CreateTriggerSkill{
  name = "joy__gongqing",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and data.from then
      return data.from:getAttackRange() >= 3 or data.damage > 1
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if data.from:getAttackRange() < 3 then
      data.damage = 1
      player:broadcastSkillInvoke(self.name, 1)
      room:notifySkillInvoked(player, self.name, "defensive")
    elseif data.from:getAttackRange() > 3 then
      player:drawCards(1, self.name)
      player:broadcastSkillInvoke(self.name, 2)
      room:notifySkillInvoked(player, self.name, "drawcard")
    end
  end,
}
panjun:addSkill(guanwei)
panjun:addSkill(gongqing)
Fk:loadTranslationTable{
  ["joy__panjun"] = "潘濬",
  ["#joy__panjun"] = "方严疾恶",
  ["joy__guanwei"] = "观微",
  [":joy__guanwei"] = "每回合限一次，一名角色的出牌阶段结束时，若其于此回合内使用过相同花色的牌，你可弃置一张牌，令其摸两张牌，然后其获得一个额外的出牌阶段。",
  ["joy__gongqing"] = "公清",
  [":joy__gongqing"] = "锁定技，当你受到伤害时，若伤害来源攻击范围小于3，则你只受到1点伤害；若伤害来源攻击范围不小于3，你摸一张牌。",
  ["#joy__guanwei-invoke"] = "观微：你可以弃置一张牌，令 %dest 摸两张牌并执行一个额外的出牌阶段",
}



local lidian = General(extension, "joy__lidian", "wei", 3)
local xunxun = fk.CreateTriggerSkill{
  name = "joy__xunxun",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and (player.phase == Player.Draw or player.phase == Player.Finish )
  end,
  on_use = function(self, event, target, player, data)
    if player.phase == Player.Draw then
      player.room:askForGuanxing(player, player.room:getNCards(4), {2, 2}, {2, 2})
    else
      player:drawCards(2,self.name,"bottom")
    end
  end,
}
lidian:addSkill(xunxun)
lidian:addSkill("wangxi")
Fk:loadTranslationTable{
  ["joy__lidian"] = "李典",
  ["joy__xunxun"] = "恂恂",
  [":joy__xunxun"] = "摸牌阶段开始时，你可以观看牌堆顶的四张牌，将其中两张牌以任意顺序置于牌堆顶，其余以任意顺序置于牌堆底。"..
  "结束阶段，你获得牌堆底的两张牌",

}

local liuxie = General(extension, "joy__liuxie", "qun", 3)
local tianming = fk.CreateTriggerSkill{
  name = "joy__tianming",
  anim_type = "defensive",
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash"
  end,
  on_cost = function(self, event, target, player, data)
    local ids = table.filter(player:getCardIds("he"), function(id) return not player:prohibitDiscard(Fk:getCardById(id)) end)
    if #ids < 3 then
      if player.room:askForSkillInvoke(player, self.name, data, "#tianming-cost") then
        self.cost_data = ids
        return true
      end
    else
      local cards = player.room:askForDiscard(player, 2, 2, true, self.name, true, ".", "#tianming-cost", true)
      if #cards > 0 then
        self.cost_data = cards
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data, self.name, player, player)
    if not player.dead then
      player:drawCards(2, self.name)
    end
    local targets = table.map(table.filter(room.alive_players, function(p) return not p:isAllNude() end), Util.IdMapper)
    local to = room:askForChoosePlayers(player,targets,1,1,"#joy__tianming",self.name,true)
    if #to > 0 then
    local p = room:getPlayerById(to[1])
    local ids = table.filter(p:getCardIds("he"), function(id) return not p:prohibitDiscard(Fk:getCardById(id)) end)
    local n = math.min(#ids,2)
    if ids == 0 then
      if room:askForSkillInvoke(p, self.name, data, "#tianming-cost") then
        player.room:drawCards(p,2, self.name)
      end
    else
      local cards = room:askForDiscard(p, n, 2, true, self.name, false, ".", "#tianming-cost")
      if #cards > 0 and not p.dead then
        room:drawCards(p, 2, self.name)
      end
    end
    end
  end,
}
local mizhao = fk.CreateActiveSkill{
  name = "joy__mizhao",
  anim_type = "control",
  min_card_num = 1,
  target_num = 1,
  can_use = function(self, player)
    return not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function(self, to_select, selected)
    return Fk:currentRoom():getCardArea(to_select) ~= Card.PlayerEquip
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local cards = effect.cards
    if player.dead or target.dead or target:isKongcheng() then return end
    room:moveCardTo(cards, Player.Hand, target, fk.ReasonGive, self.name, nil, false)
    local targets = table.filter(room:getOtherPlayers(player), function(p)
      return target:canPindian(p)
    end)
    
    if #targets == 0 then return end
    local tos = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#mizhao-choose::"..target.id, self.name, false)
    local to = room:getPlayerById(tos[1])
    local pindian = target:pindian({to}, self.name)
    if pindian.results[to.id].winner then
      local winner, loser
      if pindian.results[to.id].winner == target then
        winner = target
        loser = to
      else
        winner = to
        loser = target
      end
      if loser.dead then return end
      room:useVirtualCard("slash", nil, winner, {loser}, self.name)
    end
  end
}
liuxie:addSkill(tianming)
liuxie:addSkill(mizhao)
Fk:loadTranslationTable{
  ["joy__liuxie"] = "刘协",
  ["#joy__liuxie"] = "受困天子",

  ["joy__tianming"] = "天命",
  [":joy__tianming"] = "当你成为【杀】的目标时，你可以弃置两张牌（不足则全弃，无牌则不弃），然后摸两张牌；然后你可以选择一名角色也如此做，",
  ["joy__mizhao"] = "密诏",
  [":joy__mizhao"] = "出牌阶段限一次，你可以将任意张手牌（至少一张）交给一名其他角色。若如此做，你令该角色与你指定的另一名有手牌的角色拼点，"..
  "视为拼点赢的角色对没赢的角色使用一张【杀】。",
  ["#joy__tianming"] = "是否选择一名角色也执行一次天命",

  ["$joy__tianming1"] = " ",
  ["$joy__tianming2"] = " ",
  ["$joy__mizhao1"] = " ",
  ["$joy__mizhao2"] = " ",
  ["~joy__liuxie"] = " ",
}


local ganfuren = General(extension, "joy__ganfuren", "shu", 3, 3, General.Female)
local joy__shushen = fk.CreateTriggerSkill{
  name = "joy__shushen",
  anim_type = "support",
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self.name)
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#joy__shushen-invoke::"..target.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:loseHp(player, 1, self.name)
    if not player.dead then
      player:drawCards(1, self.name)
      target:drawCards(1, self.name)
    end
    return true
  end,
}
local joy__shushen_trigger = fk.CreateTriggerSkill{
  name = "#joy__shushen_trigger",
  mute = true,
  events = {fk.HpRecover},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill("joy__shushen")
  end,
  on_trigger = function(self, event, target, player, data)
    self.cancel_cost = false
    for i = 1, data.num do
      if self.cancel_cost then break end
      self:doCost(event, target, player, data)
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local to = room:askForChoosePlayers(player, table.map(room:getOtherPlayers(player),
      function(p) return p.id end), 1, 1, "#joy__shushen-choose", "joy__shushen", true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
    self.cancel_cost = true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke("joy__shushen")
    room:notifySkillInvoked(player, "joy__shushen")
    room:getPlayerById(self.cost_data):drawCards(1, "joy__shushen")
  end,
}
local joy__huangsi = fk.CreateTriggerSkill{
  name = "joy__huangsi",
  anim_type = "support",
  frequency = Skill.Limited,
  events = {fk.AskForPeaches},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and player.dying and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#joy__huangsi-invoke")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = player:getHandcardNum()
    room:recover({
      who = player,
      num = 1 - player.hp,
      recoverBy = player,
      skillName = self.name
    })
    player:throwAllCards("h")
    if player.dead then return end
    local to = room:askForChoosePlayers(player, table.map(room.alive_players, function(p)
      return p.id end), 1, 1, "#joy__huangsi-choose:::"..(n + 2), self.name, true)
    if #to > 0 then
      room:getPlayerById(to[1]):drawCards(n + 1, self.name)
    end
  end,
}
joy__shushen:addRelatedSkill(joy__shushen_trigger)
ganfuren:addSkill(joy__shushen)
ganfuren:addSkill(joy__huangsi)
Fk:loadTranslationTable{
  ["joy__ganfuren"] = "甘夫人",
  ["joy__shushen"] = "淑慎",
  [":joy__shushen"] = "当一名角色受到伤害时，你可以失去1点体力并防止此伤害，然后你与其各摸一张牌；当你回复1点体力后，你可以令一名其他角色摸一张牌。",
  ["joy__huangsi"] = "皇思",
  [":joy__huangsi"] = "限定技，当你处于濒死状态时，你可以回复体力至1并弃置所有手牌，然后你可以令一名角色摸X+2张牌（X为你弃置的牌数）。",
  ["#joy__shushen-invoke"] = "淑慎：你可以失去1点体力防止 %dest 受到的伤害，然后你与其各摸一张牌",
  ["#joy__shushen-choose"] = "淑慎：你可以令一名其他角色摸一张牌",
  ["#joy__huangsi-invoke"] = "皇思：你可以回复体力至1，弃置所有手牌",
  ["#joy__huangsi-choose"] = "皇思：你可以令一名角色摸%arg张牌",
}

local joy__caoang = General(extension, "joy__caoang", "wei", 4)
local joy__kangkai = fk.CreateTriggerSkill{
  name = "joy__kangkai",
  anim_type = "support",
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.card.trueName == "slash" and
    (player == target or player:distanceTo(target) == 1)
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#joy__kangkai-invoke")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:drawCards(1, self.name)
    if player == target or player:isNude() or target.dead or player:getMark("joy__kangkai-turn") == 2 then return end
    local cards = room:askForCard(player, 1, 1, true, self.name, true, ".", "#joy__kangkai-give::"..target.id)
    if #cards > 0 then
      room:addPlayerMark(player, "joy__kangkai-turn")
      room:moveCardTo(cards, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, true, player.id)
      local card = Fk:getCardById(cards[1])
      if card.type == Card.TypeEquip and not target.dead and not target:isProhibited(target, card) and not target:prohibitUse(card) and
        table.contains(target:getCardIds("h"), card.id) and
        room:askForSkillInvoke(target, self.name, data, "#kangkai-use:::"..card:toLogString()) then
        room:useCard({
          from = target.id,
          tos = {{target.id}},
          card = card,
        })
      end
    end
  end,
}
joy__caoang:addSkill(joy__kangkai)
Fk:loadTranslationTable{
  ["joy__caoang"] = "曹昂",
  ["#joy__caoang"] = "取义成仁",
  ["joy__kangkai"] = "慷忾",
  [":joy__kangkai"] = "当一名角色成为【杀】的目标后，若你与其的距离不大于1，你可以摸一张牌，然后可以交给该角色一张牌再令其展示之（每回合限两次），若此牌为装备牌，其可以使用之。",
  ["#joy__kangkai-invoke"] = "慷忾：你可以摸一张牌",
  ["#joy__kangkai-give"] = "慷忾：可以选择一张牌交给 %dest",
}


local joy__zhugedan = General(extension, "joy__zhugedan", "wei", 4)
local joy__gongao = fk.CreateTriggerSkill{
  name = "joy__gongao",
  anim_type = "support",
  frequency = Skill.Compulsory,
  events = {fk.EnterDying},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target ~= player
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:changeMaxHp(player, 1)
    if not player.dead and player:isWounded() then
      room:recover { num = 1, skillName = self.name, who = player, recoverBy = player}
    end
  end,
}
local joy__juyi = fk.CreateTriggerSkill{
  name = "joy__juyi",
  frequency = Skill.Limited,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player.maxHp > #player.room.alive_players and player:hasSkill(self) and
     player.phase == Player.Start and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name)
  end,
  on_use = function(self, event, target, player, data)
    local n = player.maxHp - #player.player_cards[Player.Hand]
    if n > 0 then
      player:drawCards(n, self.name)
    end
    player.room:handleAddLoseSkills(player, "joy__benghuai|ty_ex__weizhong")
  end,
}
joy__zhugedan:addSkill(joy__gongao)
joy__zhugedan:addSkill(joy__juyi)
joy__zhugedan:addRelatedSkill("joy__benghuai")
joy__zhugedan:addRelatedSkill("ty_ex__weizhong")
Fk:loadTranslationTable{
  ["joy__zhugedan"] = "诸葛诞",
  ["#joy__zhugedan"] = "薤露蒿里",
  ["joy__gongao"] = "功獒",
  [":joy__gongao"] = "锁定技，每当一名其他角色进入濒死状态时，你增加1点体力上限，然后回复1点体力。",
  ["joy__juyi"] = "举义",
  [":joy__juyi"] = "限定技，准备阶段，若你体力上限大于全场角色数，你可以将手牌摸至体力上限，然后获得技能〖崩坏〗和〖威重〗。",
}

local joy__guanyinping = General(extension, "joy__guanyinping", "shu", 3, 3, General.Female)
local joy__huxiao = fk.CreateTriggerSkill{
  name = "joy__huxiao",
  anim_type = "offensive",
  events = {fk.Damage},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target and data.damageType == fk.FireDamage and not data.to.dead
  end,
  on_use = function(self, event, target, player, data)
    if data.to.dead then return end
    local mark = data.to:getTableMark("@@joy__huxiao-turn")
    table.insertIfNeed(mark, player.id)
    player.room:setPlayerMark(data.to, "@@joy__huxiao-turn", mark)
  end,
}
local joy__huxiao_targetmod = fk.CreateTargetModSkill{
  name = "#joy__huxiao_targetmod",
  bypass_times = function(self, player, skill, scope, card, to)
    return table.contains(to:getTableMark( "@@joy__huxiao-turn"), player.id)
  end,
}
joy__huxiao:addRelatedSkill(joy__huxiao_targetmod)
local joy__wuji = fk.CreateTriggerSkill{
  name = "joy__wuji",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  frequency = Skill.Wake,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  can_wake = function(self, event, target, player, data)
    local n = 0
    player.room.logic:getActualDamageEvents( 1, function(e)
      local damage = e.data[1]
      n = n + damage.damage
      if n > 2 then return true end
    end)
    return n > 2
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:changeMaxHp(player, 1)
    if player:isWounded() and not player.dead then
      room:recover({ who = player, num = 1, recoverBy = player, skillName = self.name })
    end
    if player.dead then return end
    for _, id in ipairs(Fk:getAllCardIds()) do
      if Fk:getCardById(id).name == "blade" then
        if room:getCardArea(id) == Card.DrawPile or room:getCardArea(id) == Card.DiscardPile or room:getCardArea(id) == Card.PlayerEquip then
          room:moveCardTo(id, Card.PlayerHand, player, fk.ReasonPrey, self.name)
          break
        end
      end
    end
  end,
}
joy__guanyinping:addSkill("ol__xuehen")
joy__guanyinping:addSkill(joy__huxiao)
joy__guanyinping:addSkill(joy__wuji)
Fk:loadTranslationTable{
  ["joy__guanyinping"] = "关银屏",
  ["#joy__guanyinping"] = "武姬",

  ["joy__huxiao"] = "虎啸",
  [":joy__huxiao"] = "锁定技，当你对一名角色造成火焰伤害后，本回合你对其使用牌无次数限制。",
  ["@@joy__huxiao-turn"] = "虎啸",
  ["joy__wuji"] = "武继",
  [":joy__wuji"] = "觉醒技，结束阶段，若你本回合造成过至少3点伤害，你加1点体力上限并回复1点体力，，然后从牌堆、弃牌堆或场上获得【青龙偃月刀】。",
}

local joyex__sunqian = General(extension, "joyex__sunqian", "shu", 3)
local joyex__qianya = fk.CreateTriggerSkill{
  name = "joyex__qianya",
  anim_type = "support",
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.type == Card.TypeTrick and not player:isKongcheng()
  end,
  on_cost = function(self, event, target, player, data)
    local tos, cards = player.room:askForChooseCardsAndPlayers(player, 1, player:getHandcardNum(), table.map(player.room:getOtherPlayers(player), Util.IdMapper), 1, 1, ".", "#joyex__qianya-invoke", self.name, true)
    if #tos > 0 and #cards > 0 then
      self.cost_data = {tos[1], cards}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    player.room:moveCardTo(self.cost_data[2], Card.PlayerHand, player.room:getPlayerById(self.cost_data[1]), fk.ReasonGive, self.name, "", true, player.id)
    local room = player.room
    local cards = room:getCardsFromPileByRule(".|.|.|.|.|^Equip")
    if #cards > 0 and not player.dead then
      local get = cards[1]
      local card = Fk:getCardById(get)
      room:obtainCard(player, get, false, fk.ReasonDraw)
    end
  end,
}

joyex__sunqian:addSkill(joyex__qianya)
joyex__sunqian:addSkill("shuimeng")
Fk:loadTranslationTable{
  ["joyex__sunqian"] = "界孙乾",
  ["#joyex__sunqian"] = "折冲樽俎",

  ["joyex__qianya"] = "谦雅",
  [":joyex__qianya"] = "当你成为锦囊牌的目标后，你可以将任意张手牌交给一名其他角色,并从牌堆获得一张非装备牌。",
  ["#joyex__qianya-invoke"] = "谦雅：你可以将任意张手牌交给一名其他角色并获得一张非装备牌",

}

local xizhicai = General(extension, "joy__xizhicai", "wei", 3)
local updataXianfu = function (room, player, target)
  local mark = player:getTableMark("xianfu")
  table.insertIfNeed(mark[2], target.id)
  room:setPlayerMark(player, "xianfu", mark)
  local names = table.map(mark[2], function(pid) return Fk:translate(room:getPlayerById(pid).general) end)
  room:setPlayerMark(player, "@xianfu", table.concat(names, ","))
end
local chouce = fk.CreateTriggerSkill{
  name = "joy__chouce",
  anim_type = "masochism",
  events = {fk.Damaged},
  on_trigger = function(self, event, target, player, data)
    self.cancel_cost = false
    for i = 1, data.damage do
      if self.cancel_cost or not player:hasSkill(self) then break end
      self:doCost(event, target, player, data)
    end
  end,
  on_cost = function(self, event, target, player, data)
    if player.room:askForSkillInvoke(player, self.name, data) then
      return true
    end
    self.cancel_cost = true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local judge = {
      who = player,
      reason = self.name,
      pattern = ".|.|^nosuit",
    }
    room:judge(judge)
    if judge.card.color == Card.Red then
      local targets = table.map(room.alive_players, Util.IdMapper)
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#joy__chouce-draw", self.name, false)
      local to = room:getPlayerById(tos[1])
      local num = 1
      local mark = player:getTableMark( "xianfu")
      if #mark > 0 and table.contains(mark[1], to.id) then
        num = 2
        updataXianfu (room, player, to)
      end
      to:drawCards(num, self.name)
    elseif judge.card.color == Card.Black then
      local targets = table.map(table.filter(room.alive_players, function(p) return not p:isAllNude() end), Util.IdMapper)
      if #targets == 0 then return end
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#joy__chouce-discard", self.name, false)
      local to = room:getPlayerById(tos[1])
      local card = room:askForCardChosen(player, to, "hej", self.name)
      room:obtainCard(player,card,false, fk.ReasonPrey)
    end
  end,
}
xizhicai:addSkill("xianfu")
xizhicai:addSkill("tiandu")
xizhicai:addSkill(chouce)
Fk:loadTranslationTable{
  ["joy__xizhicai"] = "戏志才",
  ["#joy__xizhicai"] = "负俗的天才",

  ["joy__chouce"] = "筹策",
  [":joy__chouce"] = "当你受到1点伤害后，你可以进行判定，若结果为：黑色，你获得一名角色区域里的一张牌；红色，你令一名角色摸一张牌（先辅的角色摸两张）。",

  ["#joy__chouce-draw"] = "筹策: 令一名角色摸一张牌（若为先辅角色则摸两张）",
  ["#joy__chouce-discard"] = "筹策: 获得一名角色区域里的一张牌",

}



local zhoufang = General(extension, "joy__zhoufang", "wu", 3)
local joy__youdi = fk.CreateTriggerSkill{
  name = "joy__youdi",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish and not player:isKongcheng()
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room:getOtherPlayers(player), function(p)
      return p.id end), 1, 1, "#joy__youdi-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local card = room:askForCardChosen(to, player, "h", self.name)
    room:throwCard({card}, self.name, player, to)
    if player.dead or to.dead then return end
    if Fk:getCardById(card).trueName ~= "slash" and not to:isNude() then
      local card2 = room:askForCardChosen(player, to, "he", self.name)
      room:obtainCard(player, card2, false, fk.ReasonPrey)
      if player.dead then return end
      player:drawCards(1, self.name)
    end
    if Fk:getCardById(card).color ~= Card.Black and player.maxHp < 5 and not player.dead then
      room:changeMaxHp(player, 1)
    end
  end,
}
zhoufang:addSkill("duanfa")
zhoufang:addSkill(joy__youdi)
Fk:loadTranslationTable{
  ["joy__zhoufang"] = "周鲂",
  ["joy__youdi"] = "诱敌",
  [":joy__youdi"] = "结束阶段，你可以令一名其他角色弃置你一张手牌，若弃置的牌不是【杀】，则你获得其一张牌并摸一张牌；若弃置的牌不是黑色，且你的体力上限小于5，则你增加1点体力上限。",
  ["#joy__youdi-choose"] = "诱敌：令一名角色弃置你手牌，若不是【杀】，你获得其一张牌并摸一张牌；若不是黑色，你加1点体力上限",
}

local lvdai = General(extension, "joy__lvdai", "wu", 4)
local qinguo = fk.CreateTriggerSkill{
  name = "joy__qinguo",
  mute = true,
  events = {fk.CardUseFinished, fk.AfterCardsMove,fk.Damage},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player.phase ~= Player.NotActive then
      if event == fk.CardUseFinished then
        return target == player and data.card.type == Card.TypeEquip
      elseif event == fk.AfterCardsMove then
        local equipnum = #player:getCardIds("e")
        for _, move in ipairs(data) do
          for _, info in ipairs(move.moveInfo) do
            if move.from == player.id and info.fromArea == Card.PlayerEquip then
              equipnum = equipnum + 1
            elseif move.to == player.id and move.toArea == Card.PlayerEquip then
              equipnum = equipnum - 1
            end
          end
        end
        return #player:getCardIds("e") ~= equipnum and #player:getCardIds("e") >= player.hp and player:isWounded()
      elseif event == fk.Damage then
        return target == player and player:hasSkill(self) and data.card and data.card.skillName and table.contains(data.card.skillNames,self.name)
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.CardUseFinished then
      local room = player.room
      local success, dat = room:askForUseActiveSkill(player, "joy__qinguo_viewas", "#joy__qinguo-ask", true)
      if success then
        self.cost_data = dat
        return true
      end
    else
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if event == fk.CardUseFinished then
      room:notifySkillInvoked(player, self.name, "offensive")
      local card = Fk.skills["joy__qinguo_viewas"]:viewAs(self.cost_data.cards)
      room:useCard{
        from = player.id,
        tos = table.map(self.cost_data.targets, function(id) return {id} end),
        card = card,
        extraUse = true,
      }
    elseif event == fk.AfterCardsMove then
      room:notifySkillInvoked(player, self.name, "support")
      room:recover{
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name,
      }
    elseif event == fk.Damage then
      player:drawCards(1,self.name)
    end
  end,
}
local qinguo_viewas = fk.CreateViewAsSkill{
  name = "joy__qinguo_viewas",
  pattern = "slash",
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    local card = Fk:cloneCard("slash")
    card.skillName = "joy__qinguo"
    return card
  end,
}
local qinguo_targetmod = fk.CreateTargetModSkill{
  name = "#joy__qinguo_targetmod",
  bypass_times = function(self, player, skill, scope, card)
    return card and table.contains(card.skillNames, "joy__qinguo")
  end,
}
Fk:addSkill(qinguo_viewas)
qinguo:addRelatedSkill(qinguo_targetmod)
lvdai:addSkill(qinguo)
Fk:loadTranslationTable{
  ["joy__lvdai"] = "吕岱",
  ["#joy__lvdai"] = "清身奉公",
  
  ["joy__qinguo"] = "勤国",
  [":joy__qinguo"] = "当你于回合内使用装备牌结算结束后，你可视为使用一张不计次数限制的【杀】，且此【杀】造成伤害后你摸一张牌；当你的装备区里的牌数变化后，"..
  "若你装备区里的牌数大于等于你的体力值，你回复1点体力。",
  ["joy__qinguo_viewas"] = "勤国",
  ["#joy__qinguo-ask"] = "勤国：你可以视为使用一张不计次数限制的【杀】，此【杀】造成伤害后你摸一张牌。",

}

return extension